<template>
  <div class="app-container">
    <!--筛选条件-->
    <div class="filter-container">
      <el-select v-model="queryParams.aspect" placeholder="一级成果类型" style="width: 140px" class="filter-item search-item">
        <el-option
          v-for="item in enumList.list1"
          :key="item.value1"
          :label="item.label1"
          :value="item.value1"
        />
      </el-select>
      <el-select v-model="queryParams.item" placeholder=" 二级成果类型" style="width: 160px" class="filter-item search-item">
        <el-option
          v-for="item in enumList.list2"
          :key="item.value2"
          :label="item.label2"
          :value="item.value2"
        />
      </el-select>
      <el-select v-model="queryParams.level" placeholder="三级成果类型" class="filter-item search-item">
        <el-option
          v-for="item in enumList.list3"
          :key="item.value3"
          :label="item.label3"
          :value="item.value3"
        />
      </el-select>
      <el-select v-model="queryParams.auditFilter" placeholder="审核状态" style="width: 140px" class="filter-item search-item">
        <el-option
          v-for="item in enumList.auditList"
          :key="item.value4"
          :label="item.label4"
          :value="item.value4"
        />
      </el-select>
      <!--按日期查找-->
      <el-date-picker
        v-model="queryParams.timeRange"
        class="filter-item search-item date-range-item"
        :start-placeholder="$t('zzydefine.startdate')"
        :end-placeholder="$t('zzydefine.enddate')"
        value-format="yyyyMMdd"
        type="daterange"
        align="right"
        unlink-panels
        :picker-options="pickerOptions"
      />
      <!--开始搜索-->
      <el-button class="filter-item" type="primary" @click="search">
        {{ $t('table.search') }}
      </el-button>
      <!--重置搜索条件-->
      <el-button class="filter-item" type="success" @click="reset">
        {{ $t('table.reset') }}
      </el-button>
    </div>
    <!--表格内容 :data="tableData" -->
    <el-table
      :key="tableKey"
      ref="table"
      v-loading="loading"
      :data="list"
      border
      fit
      style="width: 100%"
      @sort-change="sortChange"
    >
      <!--选择框-->
      <!--      <el-table-column-->
      <!--        type="selection"-->
      <!--        width="55"-->
      <!--      />-->
      <!--序号-->
      <el-table-column
        align="center"
        type="index"
        label="序号"
        width="45"
        style="padding-bottom: 20px;"
      />
      <!--成果类型-->
      <el-table-column
        align="center"
        prop="type"
        label="成果类型"
        min-width="360"
      />
      <!--成果名称-->
      <el-table-column
        align="center"
        prop="name"
        label="成果名称"
        min-width="180"
      />
      <!--      &lt;!&ndash;成果状态&ndash;&gt;-->
      <!--      <el-table-column-->
      <!--        align="center"-->
      <!--        prop="auditState"-->
      <!--        label="成果状态"-->
      <!--        min-width="110"-->
      <!--        :filters="[-->
      <!--          {text: '未审批', value: '未审批' }, //text用于显示有哪些可供筛选，value筛选具体的值（text可见，value控制）-->
      <!--          {text: '通过', value: '通过' },-->
      <!--          {text: '拒绝', value: '拒绝' },-->
      <!--          {text: '重审', value: '重审'},-->
      <!--          {text: '退回', value: '退回'}-->
      <!--        ]"-->
      <!--        :filter-method="filterAuditstate"-->
      <!--        filter-placement="bottom-end"-->
      <!--      >-->
      <!--        <template slot-scope="scope">-->
      <!--          <el-tag-->
      <!--            :type="(scope.row.auditState === '已审核通过') ?'success':-->
      <!--              (scope.row.auditState === '未审核')?'info':-->
      <!--              'danger'"-->
      <!--            disable-transitions-->
      <!--          >{{ scope.row.auditState }}-->
      <!--          </el-tag>-->
      <!--          <el-tag-->
      <!--            :type="(scope.row.tag1 === '通过')? 'success':-->
      <!--              (scope.row.tag1 === '退回')? 'warning':-->
      <!--              (scope.row.tag1 === '未审批') ? 'info':-->
      <!--              (scope.row.tag1 === '拒绝') ? 'danger':-->
      <!--              (scope.row.tag1 === '重审') ? 'primary':-->
      <!--              'info'"-->
      <!--            disable-transitions-->
      <!--          >{{ scope.row.auditState }}-->
      <!--          </el-tag>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <!--成果状态-->
      <el-table-column
        align="center"
        prop="auditState"
        label="成果状态"
        min-width="110"
      >
        <template slot-scope="scope">
          <el-tag
            :type="(scope.row.auditState === '通过')? 'success':
              (scope.row.auditState === '退回')? 'warning':
              (scope.row.auditState === '未审批') ? 'info':
              (scope.row.auditState === '拒绝') ? 'danger':
              (scope.row.auditState === '重审') ? 'primary':
              'info'"
            disable-transitions
          >{{ scope.row.auditState }}
          </el-tag>
        </template>
      </el-table-column>
      <!--成果是否正向-->
      <el-table-column
        align="center"
        prop="ifPositive"
        label="加分项/减分项"
        min-width="120"
      >
        <template slot-scope="scope">
          <el-tag
            :type="(scope.row.ifPositive === '加分项' ?'success':'danger')"
            disable-transitions
          >{{ scope.row.ifPositive }}
          </el-tag>
        </template>
      </el-table-column>
      <!--获得时间-->
      <el-table-column
        align="center"
        prop="date"
        label="获得时间"
        column-key="date"
        min-width="150"
        sortable="custom"
      />
      <el-table-column
        align="center"
        fixed="right"
        label="操作"
        min-width="110"
        style="text-align: center"
      >
        <template slot-scope="scope" style="text-align: center">
          <!-- 查看+编辑+删除 -->
          <i class="el-icon-view table-operation" style="color: #87d068;" @click="handleView(scope.$index, scope.row)" />
          <i v-if=" (scope.row.auditState==='未审批') || (scope.row.auditState==='退回') " class="el-icon-edit table-operation" style="color: #2db7f5;" @click="handleEdit(scope.row)" />
          <i v-if=" (scope.row.auditState==='未审批') || (scope.row.auditState==='退回') " class="el-icon-delete table-operation" style="color: #f50;" @click="handleDelete(scope.$index, scope.row)" />
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="pagination.num"
      :limit.sync="pagination.size"
      @pagination="search"
    />
    <!--删除操作对话框-->
    <el-dialog
      title="提醒"
      :visible.sync="dialogDeletevisible"
      width="30%"
    >
      <span>{{ this.$t('tips.confirmDelete') }}</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogDeletevisible = false">取 消</el-button>
        <el-button type="primary" @click="awardDelete()">确 定</el-button>
      </span>
    </el-dialog>
    <!--引入编辑、查看对话框-->
    <user-view
      ref="view"
      :dialog-visible="dialogViewVisible"
      @close="viewClose"
    />
    <user-edit
      ref="edit"
      :dialog-visible="dialog.isVisible"
      :title="dialog.title"
      @success="editSuccess"
      @close="editClose"
    />
  </div>
</template>
<script>
import { getToken } from '@/utils/auth'
import Pagination from '@/components/Pagination'
import UserView from './View'
import UserEdit from './Edit'

export default {
  components: { Pagination, UserView, UserEdit },
  data() {
    return {
      true: true,
      // 用于筛选的下拉框内容
      enumList: {
        list1: [],
        list2: [],
        list3: [],
        auditList: [
          {
            value4: '通过',
            label4: '通过'
          },
          {
            value4: '拒绝',
            label4: '拒绝'
          },
          {
            value4: '重审',
            label4: '重审'
          },
          {
            value4: '退回',
            label4: '退回'
          },
          {
            value4: '未审批',
            label4: '未审批'
          }
        ]
      },
      // 用于选择表格内容
      // multipleSelection: [],
      // 删除数据
      dialogDeletevisible: false,
      rowData: null,
      // 查看数据
      dialogViewVisible: false,
      // 编辑数据
      dialog: {
        isVisible: false,
        title: ''
      },
      // 页面控制
      total: 0,
      pagination: {
        size: 10,
        num: 1
      },
      // 筛选查询数据
      queryParams: {},
      sort: {},
      // 表格相关
      tableKey: 0,
      loading: false,
      list: [],
      dat1: null,
      // 快捷日期查询
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      }
    }
  },
  computed: {
    currentUser() {
      return this.$store.state.account.user
    }
  },
  mounted() {
    this.fetchenumList()
    this.reset()
    this.$forceUpdate()
  },
  methods: {
    fetch() {
      return getToken()
    },
    // 下拉框函数集成
    fetchenumList(params = {}) {
      // aspect
      params.colName = 'as_scoring_aspect'
      this.$get('achievement/award/queryAwardAttr', {
        ...params
      }).then((r) => {
        const data = r.data.data
        for (let i = 0; i < data.stateItemsValue.length; i++) {
          this.enumList.list1.push(
            {
              value1: data.stateItemsValue[i],
              label1: data.stateItemsValue[i]
            })
        }
      })
      // item
      params = {}
      params.colName = 'as_scoring_item'
      this.$get('achievement/award/queryAwardAttr', {
        ...params
      }).then((r) => {
        const data = r.data.data
        for (let i = 0; i < data.stateItemsValue.length; i++) {
          this.enumList.list2.push(
            {
              value2: data.stateItemsValue[i],
              label2: data.stateItemsValue[i]
            })
        }
      })
      // level
      params = {}
      params.colName = 'as_award_level'
      this.$get('achievement/award/queryAwardAttr', {
        ...params
      }).then((r) => {
        const data = r.data.data
        for (let i = 0; i < data.stateItemsValue.length; i++) {
          this.enumList.list3.push(
            {
              value3: data.stateItemsValue[i],
              label3: data.stateItemsValue[i]
            })
        }
      })
    },
    // 表格排序（按照获得时间,not functional）
    sortChange(val) {
      this.sort.field = val.prop
      this.sort.order = val.order
      this.search()
    },
    // 函数入口
    search() {
      this.list = []
      this.$refs.table.clearSort()
      this.$refs.table.clearFilter()
      this.fetchType({
        date1: this.queryParams.timeRange[0],
        date2: this.queryParams.timeRange[1],
        // keywordsInName: this.queryParams.awardName,
        type: this.queryParams.aspect,
        item: this.queryParams.item,
        level: this.queryParams.level,
        auditFilter: this.queryParams.auditFilter
      })
    },
    // 重置筛选
    reset() {
      this.queryParams = {
        aspect: '',
        item: '',
        level: '',
        awardName: '',
        timeRange: ['', ''],
        auditFilter: ''
      }
      this.sort = {}
      this.$refs.table.clearSort()
      this.$refs.table.clearFilter()
      this.search()
    },
    fetchType(params = {}) {
      params.pageNum = this.pagination.num
      params.showPerPage = this.pagination.size
      console.log(params)
      // 根据不同的筛选条件赋给uri不同的内容
      const queryUri = 'achievement/award/jointQueryStuAward'
      this.loading = true
      this.$get(queryUri, {
        ...params
      }).then((r) => {
        console.log(r.data.data)
        this.dat1 = r.data.data
        this.total = this.dat1[0].total
        if (this.total) {
          this.list = []
          for (var i = 0; i < this.dat1.length; i++) {
            this.fetchTable(params = {}, i)
          }
          // this.$message({
          //   message: '查询成功',
          //   type: 'success'
          // })
        } else {
          this.$message({
            message: '当前暂无成果',
            type: 'warning'
          })
        }
      })
        // eslint-disable-next-line handle-callback-err
        .catch(function(error) { // 请求失败处理
          alert('Something went wrong, Please check!')
          console.log(error)
        })
    },
    fetchTable(params = {}, i) {
      params.aIndex = this.dat1[i].aindex
      this.$get('achievement/award/getAwardAttrByStuAwardIndex', {
        ...params
      }).then((r) => {
        const data = r.data.data
        this.loading = false
        if (data.isPositive) {
          data.isPositive = '加分项'
        } else {
          data.isPositive = '减分项'
        }
        // 向控制表格内容的数组中添加数据
        this.list.push(
          {
            awardInformations: data.awardInformations,
            enumValue: data.enumValue,
            inputType: data.inputTypes,
            // createTime: data.createTime.slice(0, 10),
            aIndex: this.dat1[0].allAIndex[i],
            relations: data.relations,
            // 分割线
            type: data.scoringAspect + ' -- ' + data.scoringItem + ' -- ' + data.awardLevel,
            name: data.name,
            auditState: data.auditCondition,
            ifPositive: data.isPositive.toString(),
            // eslint-disable-next-line valid-typeof
            date: data.date.slice(0, 4) + '年' + data.date.slice(4, 6) + '月' + data.date.slice(6, 8) + '日'
          })
        // 用于解决在页面条数切换时的Bug
        for (var m = 0; m < this.list.length; m++) {
          for (var n = m + 1; n < this.list.length; n++) {
            if (this.list[m].aIndex === this.list[n].aIndex) { this.list.splice(n, 1) }
          }
        }
      })
    },
    // 用于表格筛选：成果审核状态
    // filterAuditstate(value, row) {
    //   return row.auditState === value
    // },
    // 编辑成果
    handleEdit(row) {
      this.$refs.edit.setIndexs(row)
      this.dialog.title = this.$t('common.edit')
      this.dialog.isVisible = true
      // let roleId = []
      // if (row.roleId && typeof row.roleId === 'string') {
      //   roleId = row.roleId.split(',')
      //   row.roleId = roleId
      // }
      // this.$get(`system/user/${row.userId}`).then((r) => {
      //   // row.deptIds = r.data.data
      //   this.$refs.edit.setIndexs(row)
      //   this.dialog.title = this.$t('common.edit')
      //   this.dialog.isVisible = true
      // })
    },
    editClose() {
      this.dialog.isVisible = false
      this.search()
    },
    editSuccess() {
      this.dialog.isVisible = false
      this.reset()
      this.rowData = null
    },
    // 查看成果
    handleView(index, row) {
      this.$refs.view.setacIndex(row)
      this.dialogViewVisible = true
    },
    viewClose() {
      this.dialogViewVisible = false
    },
    // 删除成果
    handleDelete(index, row) {
      this.$confirm(this.$t('tips.confirmDelete'), this.$t('common.tips'), {
        confirmButtonText: this.$t('common.confirm'),
        cancelButtonText: this.$t('common.cancel'),
        type: 'warning'
      }).then(() => {
        this.rowData = row
        this.awardDelete({ aIndex: this.rowData.aIndex })
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    awardDelete(params = {}) {
      this.dialogDeletevisible = false
      // params.acIndex = this.rowData.acIndex
      this.$delete('achievement/award/deleteAward', {
        ...params
      }).then((r) => {
        console.log(r.data.message)
        // this.$message({
        //   showClose: true,
        //   message: '成果删除成功！',
        //   type: 'success'
        // })
        this.search()
      })
      this.rowData = null
    }
    // 选择框发生改变的时候响应函数
    // handleSelectionChange(val) {
    //   // 该数据即为选中的行的内容
    //   this.multipleSelection = val
    // }
  }
}
</script>
<style lang="scss" scoped>
</style>

